/*
 * Copyright (C) 2007-2008  Hylke van der Schaaf
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, in version 3 of the License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package hextd.message;

import hextd.message.MessageFactory.NetworkMessage;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MessageError implements Message {

	public enum ErrorType {

		Unknown,
		AuthFailed,
		ReplayLoadFailed
	}
	public MessageFactory.NetworkMessage type = NetworkMessage.Error;
	public static String RegExp = "ERROR (\\S+) (\\S+)(\\n|$)";
	public static Pattern MessagePattern = Pattern.compile(MessageError.RegExp);
	//
	private String message;
	private ErrorType errorType = ErrorType.Unknown;
	private String reason;
	private int senderId = -2;

	public MessageError() {
	}

	private MessageError(String message) {
		this.message = message;
		Matcher matcher = MessageError.MessagePattern.matcher(message);
		if (matcher.matches()) {
			try {
				errorType = ErrorType.valueOf(matcher.group(1));
				reason = URLDecoder.decode(matcher.group(2), "UTF-8");
			} catch (UnsupportedEncodingException ex) {
				System.err.println(ex);
				reason = matcher.group(1);
			}
		}
	}

	public static String formatMessage(ErrorType type, String reason) {
		try {
			return "ERROR " + type.name() + " " + URLEncoder.encode(reason, "UTF-8");
		} catch (UnsupportedEncodingException ex) {
			System.err.println(ex);
			return "ERROR " + type.name() + " Unknown";
		}
	}

	public String getReason() {
		return this.reason;
	}

	public ErrorType getErrorType() {
		return errorType;
	}

	@Override
	public String getMessage() {
		return this.message;
	}

	@Override
	public Message initFromString(String message) {
		return new MessageError(message);
	}

	@Override
	public int getSenderId() {
		return this.senderId;
	}

	@Override
	public void setSenderId(int id) {
		throw new UnsupportedOperationException("Not supported yet.");
	}

	@Override
	public Pattern getPattern() {
		return MessageError.MessagePattern;
	}

	@Override
	public NetworkMessage getType() {
		return this.type;
	}
}
